<?php
/**
 * Created by PhpStorm.
 * User: LENOVO
 * Date: 2018/9/12
 * Time: 23:32
 */

namespace app\wx\controller;


use app\wx\model\XcxUserInfo;
use app\wx\WxConfig;

class XcxLogin extends WxConfig
{
  public $appId = 'wx00559721ae0d4752';
  public $appSecret = '008321f2b586169a71a857f1c072b5ca';

    public function login()
    {
        $XcxUserModel = new XcxUserInfo();
        $code = request()->param('code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$this->appId&secret=$this->appSecret&js_code=$code&grant_type=authorization_code";
        $res = $this->_request('get', $url);
        $res_result = json_decode($res, true);
        $openid = $res_result['openid'];
        $select_result = $XcxUserModel::where('openid', $openid)->find();
        if (!$select_result) {
            $res_result['id'] = null;
            $res_result['access_token'] = self::setToken();
            $addResult = $XcxUserModel->save($res_result);
            if ($addResult) {
                return json_encode([
                    'code' => 0,
                    'data' => $XcxUserModel::where('openid', $openid)->find()
                ]);
            }
        }
        return json_encode([
            'code' => 0,
            'data' => $select_result
        ]);
    }

    public static function setToken()
    {
        $str = md5(uniqid(md5(microtime(true)), true));  //生成一个不会重复的字符串
        $str = sha1($str);  //加密
        return $str;
    }

    public function postUserInfo()
    {
        $data = request()->param();
        $xcxUserModel= new XcxUserInfo();
        $result = $xcxUserModel->allowField(true)->save($data,['access_token'=>$data['access_token']]);
        if($result){
            return json([
                'code'=>0,
                'message'=>'上报成功',
            ]);
        }
    }

}